package grsu.epam.airline.DAOImpl;

import grsu.epam.airline.constant.Constant;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DAOFactory {
	private static final Logger logger = Logger.getLogger(DAOFactory.class);
	private static final String JNDI_DB_REF = "java:/comp/env/jdbc/appDb";
	private static final String JNDI_DB_REF_NOT_FOUND = "'java:/comp/env/jdbc/appDb' is not found in JNDI";
	private static DAOFactory instance;
	private Connection conn;

	private DAOFactory() {
	}

	public static DAOFactory getInstance() {
		if (instance == null) {
			instance = new DAOFactory();
		}
		return instance;
	}

	private Connection initConnection() {
		DataSource ds;
		try {
			ds = (DataSource) new InitialContext().lookup(JNDI_DB_REF);
		} catch (NamingException e) {
			throw new ExceptionInInitializerError(JNDI_DB_REF_NOT_FOUND);
		}
		if (ds != null) {
			try {
				this.conn = ds.getConnection();
			} catch (SQLException e) {
				logger.error("Connection not found!");
			}
		}
		return this.conn;
	}

	public Object getDAO(Constant nameDao) {
		Object dao = null;
		if (Constant.UserDAO.equals(nameDao)) {
			dao = new UserDAOImpl(initConnection());
		}
		if (Constant.AirportDAO.equals(nameDao)) {
			dao = new AirportDAOImpl(initConnection());
		}
		if (Constant.AirportInRouteDAO.equals(nameDao)) {
			dao = new AirportInRouteDAOImpl(initConnection());
		}
		if (Constant.EmployeeDAO.equals(nameDao)) {
			dao = new EmployeeDAOImpl(initConnection());
		}
		if (Constant.FlightCrewDAO.equals(nameDao)) {
			dao = new FlightCrewDAOImpl(initConnection());
		}
		if (Constant.FlightDAO.equals(nameDao)) {
			dao = new FlightDAOImpl(initConnection());
		}
		if (Constant.PlaneDAO.equals(nameDao)) {
			dao = new PlaneDAOImpl(initConnection());
		}
		if (Constant.SpecialityDAO.equals(nameDao)) {
			dao = new SpecialityDAOImpl(initConnection());
		}
		return dao;
	}

	public void closeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception ignore) {
			}
		}
	}
}
